<template>
  <view class="cart-coupon">
    当前门店商品可使用优惠券
    <view class="text-primary flex items-center" @click="toVisible()">
      领劵
      <image class="ml-4px" :src="ossImg('cart/right_blue.png')" />
    </view>
  </view>

  <view class="cart-list">
    <view v-for="item in saleableList" :key="item.id">
      <oreo-swipe-cell :right-width="65">
        <oreo-cell-group :border="false">
          <view class="cart-item">
            <view class="goodCheckBox" @click.stop="onChangeSelectStatus(item)">
              <view
                class="goods-checkbox"
                :class="{ checked: item.selected }"
              ></view>
            </view>

            <view class="cart-goods flex flex-1">
              <view
                class="cart-goods__cover cover"
                @click.stop="toGoodsDetail(item)"
                :style="{ backgroundImage: `url(${item.productImageUrl})` }"
              ></view>
              <view class="cart-goods__info flex-1">
                <view
                  class="goods-name line-clamp-2 flex-1"
                  @click.stop="toGoodsDetail(item)"
                >
                  {{ item.productName }}
                </view>
                <view>
                  <view
                    class="goods-sku"
                    @click.stop="getSkuData(item)"
                    v-if="item.productSkus.length > 1"
                  >
                    <label>{{
                      item.productSkuSpData[0].key +
                        "*" +
                        item.productSkuSpData[0].value || "-"
                    }}</label>
                    <image :src="ossImg('cart/right.png')" />
                  </view>
                </view>
                <view class="goods-price flex justify-between">
                  <view class="price text-primary font-bold">
                    {{ cal.cheng(item.productSkuPrice, item.quantity) }}
                  </view>
                  <stepper
                    v-model:value="item.quantity"
                    :detail="item"
                    @change="onChangeProductQuantity(item.id, $event)"
                  />
                </view>
              </view>
            </view>
          </view>
        </oreo-cell-group>

        <template v-slot:right>
          <view class="van-swipe-cell__right" @click.stop="deleteCartGood(item)"
            >删除</view
          >
        </template>
      </oreo-swipe-cell>
    </view>

    <view class="flex flex-1 cart-title" v-if="noSaleableList.length > 0">
      <view class="ml-16">以下商品已失效</view>
      <view class="font-blue" @click="cleanCart">清空失效商品</view>
    </view>

    <view v-for="item in noSaleableList" :key="item.id">
      <oreo-swipe-cell :right-width="65">
        <oreo-cell-group :border="false">
          <view class="cart-item">
            <view class="noSaleab">失效</view>
            <view class="cart-goods flex flex-1">
              <view
                class="cart-goods__cover cover"
                :style="{ backgroundImage: `url(${item.productImageUrl})` }"
              ></view>
              <view class="cart-goods__info flex-1">
                <view class="nogoods-name line-clamp-2 flex-1">
                  {{ item.productName }}
                </view>
                <view>
                  <view class="goods-sku">
                    <label>{{
                      item.productSkuSpData[0].key +
                        "*" +
                        item.productSkuSpData[0].value || "-"
                    }}</label>
                    <image :src="ossImg('cart/right.png')" />
                  </view>
                </view>
                <view class="goods-price flex justify-between">
                  <view class="text-primary font-bold nos-font">
                    所选规格已售罄
                  </view>
                  <button class="primary" @click.stop="getSkuData(item)">
                    重选规格
                  </button>
                </view>
              </view>
            </view>
          </view>
        </oreo-cell-group>

        <template v-slot:right>
          <view class="van-swipe-cell__right" @click.stop="deleteCartGood(item)"
            >删除</view
          >
        </template>
      </oreo-swipe-cell>
    </view>
  </view>

  <view class="submit-view">
    <view class="cart-submit">
      <view
        class="flex items-center text-s text-goods"
        @click.stop="onChangeSelectAll"
      >
        <view
          class="goods-checkbox mr-13px"
          :class="{ checked: props.allSelect }"
        ></view>
        <view>全选</view>
      </view>
      <view class="flex items-center">
        <view>
          <view class="flex items-end justify-end text-s leading-none mb-5px">
            合计：
            <view class="price text-primary font-bold text-16px">
              {{ info.finalPrice }}
              <!--            <label>.80</label>-->
            </view>
          </view>
          <view
            class="cart-total"
            v-if="info.items.some((item) => item.selected)"
          >
            已优惠：¥{{ info.couponPrice || 0 }}
            <view class="flex items-end ml-12px" @click="isShowDetail">
              优惠明细
              <image
                :src="ossImg('cart/right_blue.png')"
                :style="{
                  transform: `rotate(${
                    props.preferenceVisible === true ? '90deg' : '270deg'
                  })`,
                }"
              />
            </view>
          </view>
        </view>
        <button class="submit" @click.stop="onCreateOrder">结算</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import Stepper from "@/components/stepper.vue";
import { defineProps, defineEmits, watch } from "vue";
import { GetGoodsSku } from "@/services/mall";
import {
  UpdateCartQuantity,
  UpdateCartSelectStatus,
  CartAllSelectStatus,
  CleanCart,
  DeleteCartItem,
} from "@/services/cart";
import { message } from "@/utils/utils";
import { ref } from "vue";
import { ossImg } from "@/utils/utils";
import { cal } from "@/utils/cal";

const emits = defineEmits([
  "sku-change",
  "openVisible",
  "getInfo",
  "showDetail",
]);

const props = defineProps({
  info: {
    type: Object,
    default: () => ({
      items: [],
    }),
  },
  allSelect: {
    type: Boolean,
  },
  preferenceVisible: {
    type: Boolean,
  },
});

const saleableList = ref([]);
const noSaleableList = ref([]);

watch(
  () => props.info,
  (newVal) => {
    console.log("监听porps");
    let sList = [];
    let noSList = [];
    for (const item of newVal.items) {
      if (item.saleable === true && item.inStock !== 0) {
        sList.push(item);
      } else if (item.saleable === false || item.inStock === 0) {
        noSList.push(item);
      }
    }
    saleableList.value = sList;
    noSaleableList.value = noSList;
  },
  {
    immediate: true, // 这个属性是重点啦
    deep: true, // 深度监听的参数
  }
);

// 前往订单生成页面
const onCreateOrder = () => {
  getApp().emdlz(
    "track",
    "event",
    "store_page",
    "click",
    "balance_button",
    `${props.info.finalPrice}`
  );
  if (!props.info.items.some((item) => item.selected)) {
    uni.showToast({
      title: "请选择商品",
      icon: "none",
    });
    return;
  }

  if (props.info.couponId !== null) {
    uni.navigateTo({
      url: "/pages/goods/order?couponId=" + props.info.couponId,
    });
  } else {
    uni.navigateTo({ url: "/pages/goods/order" });
  }
};

// 获取SKU以及展开选择面板
const getSkuData = async (product) => {
  console.log(product);
  emits("sku-change", product);
};

const toVisible = () => {
  getApp().emdlz("track", "event", "store_page", "click", "get_coupon", "");
  emits("openVisible", true);
};

const isShowDetail = () => {
  emits("showDetail", true);
};

// 全选
const onChangeSelectAll = async () => {
  const res = await CartAllSelectStatus();
  if (res?.code === 200) {
    emits("getInfo");
  } else {
    message(res.message);
  }
};

// 修改选中状态
const onChangeSelectStatus = async ({ id, selected }) => {
  const res = await UpdateCartSelectStatus({ id, selected: selected ? 0 : 1 });
  if (res?.code === 200) {
    emits("getInfo");
  } else {
    message(res.message);
  }
};

const deleteCartGood = async (item) => {
  const res = await DeleteCartItem(item.id);
  if (res?.code === 200) {
    getApp()
      .sr()
      .track("add_to_cart", {
        action_type: "remove_from_cart",
        sku: {
          sku_id: item.productSkuId,
          sku_name: skuLabel(item.productSkuSpData),
        },
        spu: {
          spu_id: item.productSkuId, // 若商品无spu_id时，可传sku_id信息
          spu_name: skuLabel(item.productSkuSpData), // 若商品无spu_name时，可传sku_name信息
        },
        sku_num: item.quantity,
        // more...
      });
    emits("getInfo");
  } else {
    message(res.message);
  }
};

const cleanCart = async () => {
  const res = await CleanCart();
  if (res?.code === 200) {
    message("清除成功~");
    emits("getInfo");
  } else {
    message(res.message);
  }
};

// 修改购物车数量
const onChangeProductQuantity = async (id, quantity) => {
  const res = await UpdateCartQuantity({ id, quantity });
  if (res?.code === 200) {
    emits("getInfo");
  } else {
    message(res.message);
  }
};

const toGoodsDetail = async (item) => {
  console.log(item);
  getApp().emdlz(
    "track",
    "event",
    "store_page",
    "click",
    `product_button_${item.productId}`,
    ""
  );

  for (const res of item.productSkus) {
    getApp()
      .sr()
      .track("trigger_sku_component", {
        sku: {
          sku_id: res.id, // 若商品无sku_id时，可传spu_id信息
          sku_name: skuLabel(res.spData), // 若商品无sku_name时，可传spu_name信息
        },
        spu: {
          spu_id: res.id, // 若商品无spu_id时，可传sku_id信息
          spu_name: skuLabel(res.spData), // 若商品无spu_name时，可传sku_name信息
        },
      });
  }

  uni.navigateTo({ url: `/pages/goods/goods?id=${item.productId}` });
};

const skuLabel = (skuData) => {
  return skuData.map(({ value, key }) => `${key}${value}`).join(" ");
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.submit-view {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  z-index: 999;
  position: fixed;
  left: 0;
  bottom: 50px;
  box-sizing: border-box;
  width: 100%;
}
.cart-submit {
  width: 100%;
  height: 52px;
  box-shadow: 0px -5px 5px 0px rgba(0, 0, 0, 0.04);
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px 0 8px;
  box-sizing: border-box;

  .cart-total {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: @primary-color;

    image {
      width: 5px;
      height: 9px;
      transform: rotate(-90deg);
      display: block;
      margin-left: 4px;
      margin-bottom: 3px;
    }
  }

  button.submit {
    width: 98px;
    height: 40px;
    line-height: 40px;
    background: #0058c6;
    border-radius: 20px;
    color: white;
    margin-left: 12px;
    font-size: 16px;
    font-weight: 400z;

    &::after {
      border: none;
    }
  }
}

.cart-list {
  padding: 20px 0 0 0;
}

.cart-item {
  display: flex;
  align-items: center;
  margin-bottom: 31px;
  // &:last-child {
  //   margin-bottom: 0;
  // }
}

.cart-title {
  justify-content: space-between;
  font-size: 14px;
}

.font-blue {
  color: #0058c6;
}

.ml-16 {
  margin-left: 35px;
  margin-bottom: 20px;
}

.noSaleab {
  font-size: 12px;
  width: 30px;
  text-align: center;
  margin-right: 5px;
  background-color: #949494;
  border-radius: 32px;
  color: #fff;
}
.goodCheckBox {
  display: flex;
  width: 35px;
  justify-content: center;
  height: 100px;
  align-items: center;
}

.cart-goods {
  .cart-goods__cover {
    min-width: 100px;
    height: 100px;
    background: rgba(0, 0, 0, 0.1);
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }

  .goods-sku {
    text-align: center;
    height: 22px;
    line-height: 22px;
    background: #f7f7f7;
    color: #949494;
    font-size: 12px;
    display: inline-block;
    margin: 9px 0;
    padding: 0 8px 0 5px;
    box-sizing: border-box;

    image {
      width: 5px;
      height: 10px;
      transform: rotate(90deg);
      margin-left: 7px;
    }
  }

  .goods-price {
    font-size: 16px;

    label,
    &::before {
      font-size: 12px;
    }
  }

  .cart-goods__info {
    padding: 0 10px;
    padding-bottom: 2px;
    display: flex;
    flex-direction: column;

    .goods-name {
      font-size: 14px;
    }

    .nogoods-name {
      font-size: 14px;
      color: #949494;
    }
  }
}

.nos-font {
  font-weight: 500;
  font-size: 14px;
  line-height: 26px;
}

.cart-coupon {
  width: 100%;
  height: 40px;
  padding: 0 12px;
  box-sizing: border-box;
  font-size: 14px;
  display: flex;
  line-height: 1;
  justify-content: space-between;
  align-items: center;
  // margin: -12px 0 0 0;
  color: @label-color;

  image {
    width: 5px;
    height: 9px;
    display: block;
  }
}

.primary {
  color: @primary-color;
  border-color: @primary-color;
  width: 75px;
  height: 30px;
  line-height: 26px;
  margin: 0;
  border: solid 1px;
  font-size: 14px;
  background-color: #fff;
  padding: 0 5px;
  border-radius: 32px;
  box-sizing: border-box;
}

button::after {
  border: none;
}

.van-swipe-cell__right {
  display: flex;
  width: 65px;
  height: 100%;
  font-size: 14px;
  line-height: 100%;
  color: #fff;
  align-items: center;
  justify-content: center;
  background-color: #f44;
  margin-left: 10px;
}

.goods-checkbox {
  width: 18px;
  min-width: 18px;
  height: 18px;
  border-radius: 16px;
  box-sizing: border-box;
  border: 1px solid @primary-color;

  &.checked {
    border: none;
    background: url("@{ossPath}others/component/checkbox.png") no-repeat center /
      100% 100%;
  }
}
</style>
